package com.whfc.cncit.helmet.codec;

import com.whfc.cncit.constant.CncitConst;
import com.whfc.cncit.entity.CncitUpMsgR;
import com.whfc.common.util.JSONUtil;
import com.whfc.iot.util.ByteUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @Description:
 * @author: xugcheng
 * @version: 1.0
 * @date: 2019/10/25 14:44
 */
public class CncitUpMsgCodecR implements CncitMsgCodec<CncitUpMsgR> {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Override
    public CncitUpMsgR decode(String data) {
        //$13,R,131910027100001,#
        CncitUpMsgR msg = null;
        String[] dataArr = data.split(CncitConst.DELIMITER);
        if (dataArr != null && dataArr.length >= 3) {
            String deviceId = dataArr[2];
            msg = new CncitUpMsgR(deviceId);
        }
        return msg;
    }

    @Override
    public String encode(CncitUpMsgR msg) {
        //$13,R,131910027100001,#
        String dataLengthStr = ByteUtil.toHexString(msg.getDataLength());
        String data = String.format("$%s,%s,%s,#", dataLengthStr, msg.getCmd(), msg.getDeviceCode());
        logger.info("发送数据:{}", data);
        return data;
    }

    public static void main(String[] args) {
        String data = "$13,R,131910027100001,#";
        CncitUpMsgCodecR codec = new CncitUpMsgCodecR();
        CncitUpMsgR msg = codec.decode(data);
        String data1 = codec.encode(msg);
        System.out.println(data);
        System.out.println(data1);
        System.out.println(JSONUtil.toPrettyString(msg));
        System.out.println("131910027100001".length());

    }
}
